package com.sicau.rag;

import com.sicau.utils.YouDaoTranslation;
import com.sicau.utils.YouDaoTranslationFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * 自定义翻译查询转换器，使用有道api
 */
@Slf4j
public class YouDaoTranslationQueryTransformer {

    private final YouDaoTranslation youDaoTranslation;

    public YouDaoTranslationQueryTransformer(YouDaoTranslationFactory youDaoTranslationFactory) {
        this.youDaoTranslation = youDaoTranslationFactory.create();
    }

    public YouDaoTranslationQueryTransformer(String sourceLanguage, String targetLanguage, YouDaoTranslationFactory youDaoTranslationFactory) {
        this.youDaoTranslation = youDaoTranslationFactory.create(sourceLanguage, targetLanguage);
    }

    /**
     * 翻译查询
     * @param query 原始查询
     * @return 翻译后的查询
     */
    public String transform(String query) {
        if (isChinese(query)) {
            log.info("Query is Chinese. Skipping translation.");
            return query;
        }
        Assert.notNull(query, "query cannot be null");
        String translatedQueryText = youDaoTranslation.translate(query);
        if (!StringUtils.hasText(translatedQueryText)) {
            log.warn("Query translation result is null/empty. Returning the input query unchanged.");
            return query;
        } else {
            return translatedQueryText;
        }
    }

    /**
     * 判断输入的文本是否为中文
     * @param text 待判断的文本
     * @return 判断结果
     */
    private boolean isChinese(String text) {
        // 统计中文字符比例
        int chineseCount = 0;
        for (char c : text.toCharArray()) {
            if (c >= 0x4e00 && c <= 0x9fa5) {
                chineseCount++;
            }
        }
        // 如果中文字符占比超过一定阈值，则认为是中文
        return chineseCount > text.length() * 0.5;
    }

}
